package org.jeecg.modules.amazon.amazonproduct.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.exception.JeecgBootBizTipException;
import org.jeecg.modules.amazon.amazonproduct.entity.AmazonTaskProduct;
import org.jeecg.modules.amazon.amazonproduct.mapper.AmazonTaskProductMapper;
import org.jeecg.modules.amazon.amazonproduct.service.IAmazonTaskProductService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Description: 亚马逊商品表
 * @Author: jeecg-boot
 * @Date:   2025-11-12
 * @Version: V1.0
 */
@Service
public class AmazonTaskProductServiceImpl extends ServiceImpl<AmazonTaskProductMapper, AmazonTaskProduct> implements IAmazonTaskProductService {
    /**
     * 采集器--商品添加
     * @param jsonObject
     */
    @Override
    public void HttpAdd(JSONObject jsonObject) {
        String userId= jsonObject.getString("user_id");
        String taskId = jsonObject.getString("task_id");
        String gsId = jsonObject.getString("gs_id");



        if (StrUtil.isEmpty(userId) || StrUtil.isEmpty(taskId) || StrUtil.isEmpty(gsId)){
            throw new JeecgBootBizTipException("参数为空 user_id/task_id/gs_id");
        }
        //商品
        JSONArray productList = jsonObject.getJSONArray("product");
        for (Object jsonObjectData : productList) {
            // 将 LinkedHashMap 转换为 JSONObject
            AmazonTaskProduct amazonTaskProduct =formattingData((Map<String, Object>) jsonObjectData,userId,taskId,gsId);
            amazonTaskProduct.setUserId(userId);
            amazonTaskProduct.setGsId(gsId);
            amazonTaskProduct.setTaskId(taskId);
            this.baseMapper.insert(amazonTaskProduct);
        }
    }

    @Override
    public List<AmazonTaskProduct> querySkuByparentSku(String parentSku) {
        LambdaQueryWrapper<AmazonTaskProduct> amazonTaskProductLambdaQueryWrapper = new LambdaQueryWrapper<>();
        amazonTaskProductLambdaQueryWrapper.eq(AmazonTaskProduct::getParentSku,parentSku);
        amazonTaskProductLambdaQueryWrapper.eq(AmazonTaskProduct::getIsParent,"2");
        return  baseMapper.selectList(amazonTaskProductLambdaQueryWrapper);
    }

    /**
     * 封装参数
     * @param jsonObjectData
     * @param userId
     * @param taskId
     * @param gsId
     * @return
     */
    /**
     * 使用Builder模式重构
     */
    private AmazonTaskProduct formattingData(Map<String, Object> jsonObjectData, String userId, String taskId, String gsId) {
        AmazonTaskProduct amazonTaskProduct = new AmazonTaskProduct();
        // 设置普通字段
        amazonTaskProduct.setIsParent(getString(jsonObjectData, "is_parent"))
                .setTitle(getString(jsonObjectData, "title"))
                .setSku(getString(jsonObjectData, "sku"))
                .setParentSku(getString(jsonObjectData, "parent_sku"))
                .setBrand(getString(jsonObjectData, "brand"))
                .setStandardPrice(getString(jsonObjectData, "standard_price"))
                .setYunfei(getString(jsonObjectData, "yunfei"))
                .setHighPrice(getString(jsonObjectData, "high_price"))
                .setQuantity(getString(jsonObjectData, "quantity"))
                .setSize(getString(jsonObjectData, "size"))
                .setColor(getString(jsonObjectData, "color"))
                .setVariantThemes(getString(jsonObjectData, "variant_themes"))
                .setCateStr(getString(jsonObjectData, "cate_str"))
                .setNodeid(getString(jsonObjectData, "nodeid"))
                .setStartDate(getString(jsonObjectData, "start_date"))
                .setAsin(getString(jsonObjectData, "asin"))
                .setPoint1(getString(jsonObjectData, "point1"))
                .setPoint2(getString(jsonObjectData, "point2"))
                .setPoint3(getString(jsonObjectData, "point3"))
                .setPoint4(getString(jsonObjectData, "point4"))
                .setPoint5(getString(jsonObjectData, "point5"))
                .setDescription(getString(jsonObjectData, "description"))
                .setPurchase(extractPurchaseUrl(jsonObjectData))
                .setProductImage(toStringSafe(jsonObjectData.get("product_image")))
                .setCurrency(getString(jsonObjectData, "currency"))
                .setSellerUrl(getString(jsonObjectData, "seller_url"))
                .setSellerId(getString(jsonObjectData, "seller_id"))
                .setSellerName(getString(jsonObjectData, "seller_name"))
                .setSellerAddress(getString(jsonObjectData, "seller_address"))
                .setFeedbackCon(toStringSafe(jsonObjectData.get("feedback_con")))
                .setSellerRate(getString(jsonObjectData, "seller_rate"))
                .setLargeNodeRate(getString(jsonObjectData, "large_node_rate"))
                .setSmallNodeRate(getString(jsonObjectData, "small_node_rate"));

        return amazonTaskProduct;
    }

    private String getString(Map<String, Object> map, String key) {
        Object value = map.get(key);
        return value == null ? "" : value.toString();
    }

    private String toStringSafe(Object obj) {
        if (obj==null){
            return "";
        }


        return obj == null ? "" : JSONObject.toJSONString(obj);
    }

    private String extractPurchaseUrl(Map<String, Object> data) {
        List<Map<String,String>> purchase = (List<Map<String, String>>) data.get("purchase");

        if (purchase!=null){
            if (purchase.size()>0){
                Map<String, String> stringStringMap = purchase.get(0);
                String url = stringStringMap.get("url");
                if (StrUtil.isNotEmpty(url)){
                    return url;
                }

            }
        }
        return "";
    }
}
